package handlers

import (
	"domain-system/models"
	"domain-system/services"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type PaymentHandler struct {
	paymentService *services.PaymentService
}

func NewPaymentHandler(db *gorm.DB) *PaymentHandler {
	return &PaymentHandler{
		paymentService: services.NewPaymentService(db),
	}
}

// CheckPaymentStatus 检查支付状态
func (h *PaymentHandler) CheckPaymentStatus(c *gin.Context) {
	groupID := c.Query("group_id")
	applicantID := c.Query("applicant_id")

	if groupID == "" || applicantID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "group_id和applicant_id参数不能为空",
		})
		return
	}

	result, err := h.paymentService.CheckPaymentStatus(groupID, applicantID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "查询支付状态失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"data":    result,
	})
}

// CreatePayment 创建支付记录
func (h *PaymentHandler) CreatePayment(c *gin.Context) {
	var req services.CreatePaymentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误: " + err.Error(),
		})
		return
	}

	payment, err := h.paymentService.CreatePayment(&req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "创建支付记录失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"success": true,
		"data":    payment,
		"message": "支付记录创建成功",
	})
}

// UpdatePaymentStatus 更新支付状态（用于支付回调）
func (h *PaymentHandler) UpdatePaymentStatus(c *gin.Context) {
	var req struct {
		TransactionID string `json:"transaction_id" binding:"required"`
		Status        string `json:"status" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误: " + err.Error(),
		})
		return
	}

	err := h.paymentService.UpdatePaymentStatus(req.TransactionID, models.PaymentStatus(req.Status))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "更新支付状态失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "支付状态更新成功",
	})
}
